package housing.task2;

import housing.task1.actor.Address;
import housing.task1.actor.Renter;
import housing.task2.deserializator.AbstractReader;
import housing.task2.factory.JSNFactory;
import housing.task2.serializator.AbstractWriter;

import java.io.*;


/**
 * Created by IntelliJ IDEA.
 * User: Linderhof
 * Date: 30.11.2010
 * Time: 17:46:11
 */
public class SerDemo {
    public static void main(String[] args) {
        JSNFactory factory =
                new JSNFactory();
        AbstractWriter jsnWriter =
                factory.createWriter();
        AbstractReader jsnReader =
                factory.createReader();

        /*//Testing Renters write-read
        testWritingRenters(jsnWriter);
        testReadingRenters(jsnWriter, jsnReader);*/

        //Testing Address write-read
        testWritingAddress(jsnWriter);
        testReadingAddress(jsnWriter, jsnReader);
    }//main()

    private static void testReadingAddress(AbstractWriter jsnWriter, AbstractReader jsnReader) {
        System.out.println("Addresses:");
        for (Address addr : jsnReader.readAddress(jsnWriter.getAddressOut())) {
            System.out.println(addr);
        }
    }

    private static void testWritingAddress(AbstractWriter jsnWriter) {
        jsnWriter.erase(jsnWriter.getAddressOut()); //for avoiding conflict with same ID-s
        //its done for future adding file content to DB
        for (short i = 0; i < 10; i++) {
            jsnWriter.write(new Address());
        }
    }

    private static void testReadingRenters(AbstractWriter jsnWriter, AbstractReader jsnReader) {
        for (Renter renter : jsnReader.readRenter(jsnWriter.getRentersOut())) {
            System.out.println(renter);
        }
    }

    private static void testWritingRenters(AbstractWriter jsnWriter) {
        jsnWriter.erase(jsnWriter.getRentersOut()); //for avoiding conflict with same ID-s
        //its done for future adding file content to DB
        for (short i = 0; i < 10; i++) {
            jsnWriter.write(new Renter());
        }
    }

    private static void displayFile(File file) {
        FileReader reader = null;
        BufferedReader in = null;

        try {
            reader = new FileReader(file);
            in = new BufferedReader(reader);
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
